package edu.gatech.cs2340.sharks.fms;

/**
 * SearchItemActivity.java
 * @author The Invsible Man
 * 
 * Allows users to search through items
 */

import edu.gatech.cs2340.sharks.fms.data.*;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import java.util.List;

public class SearchItemActivity extends Activity
{
	/**
	 * The list of the results
	 */
	private ListView ListView1;
	
	/**
	 * The items that match the search query
	 */
	public static Item[] items;
	
	/**
	 * The item adapter for placing the items into the list
	 */
	public ItemAdapter adaptItems;
	
	/**
	 * The current instance of the activity, used to make sure there is only one instance of this activity running at a time.
	 */
	private static Activity instance = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search_item);
		
		if (instance != null) instance.finish();
		instance = this;
		
		Packet<List<Item>> ui = DBMgr.userItems(DBMgr.user); 

		if (ui.status.code() == Status.Code.OK)
		{
			List<Item> it = ui.value;
			items = new Item[it.size()];
			for (int i = 0; i < it.size(); i++) items[i] = it.get(i); // FIXME!

			ListView1 = (ListView) findViewById(R.id.searchedItemList);
			adaptItems = new ItemAdapter(this, R.layout.listview_item_row, items);
			ListView1.setAdapter(adaptItems);
			ListView1.setClickable(true); 
		}
		else Info.alert(this, ui.status.toString());
	}

	/**
	 * Calls the database search function and actually places the results into the list
	 * 
	 * @param searchString The string for which to search
	 */
	public void searchItems(String searchString)
	{
		Packet<List<Item>> si = DBMgr.search(searchString, null, null, null, null, null);
		
		if(si.status.code() == Status.Code.OK)
		{
			List<Item> sit = si.value;
			items = new Item[sit.size()];
			for (int i = 0; i < sit.size(); i++) items[i] = sit.get(i); // FIXME!
			adaptItems.notifyDataSetChanged();
		}
		else Info.alert(this, si.status.toString());
	}

	/**
	 * Goes to the item details screen to view an item
	 * 
	 * @param view The current view
	 */
	public void itemDetails(View view)
	{
		int itemID = (Integer) view.getTag(); 
		Intent toItemDetails = new Intent(this, ViewItemActivity.class);
		toItemDetails.putExtra("ItemID", itemID); 
		startActivity(toItemDetails); 
	}
}